/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 高亮近重孔 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: "unit.+",
		step2:"unit",
		auto_save: "No",
		units: 'mm'
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
    }


	var stepList = GEN.getStepList({job:job})
	// step过滤
    stepList = stepList.filter(function(step){
		var regexp = new RegExp(par.step,"ig")
		return regexp.test(step)
	})
	if (stepList.length == 0 && par.step2) {
		stepList = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	var matrix = GEN.getMatrix({job:job})

    var DrillLayer = Object.keys(matrix).reduce(function(a,b){
        if(matrix[b].context == "board" && matrix[b].layer_type == 'drill'){
            a.push(b)
        }
        return a;
    },[])
	
	if(stepList.length == 0) { throw "未发现step:"+par.step_filter }
	stepList.forEach(function(step){
		GEN.openStep({job:job, name:step})
		GEN.clearLayers();  //清除层显示
		GEN.affectedLayer({ mode: 'all', affected: 'no' });  //设置影响层全部不影响
		GEN.COM("sel_options,clear_mode=clear_after,display_mode=all_layers,area_inout=inside,area_select=select,select_mode=standard,area_touching_mode=exclude");
		GEN.units({ type: par.units });  //单位初始化
        GEN.zoomHome();  //窗口显示回到原始位置

		DrillLayer.forEach(function(drill_layer){
			var tmp_drl = drill_layer + "_tmp";
			var line_drl = drill_layer + "_line";
			GEN.workLayer({name:drill_layer,display_number:2,clear_before:'yes'})

			var tmp_chk = "tmp_chk"
			if(GEN.isChklistExists({job:job,step:step,chklist:tmp_chk})){
				GEN.COM("chklist_delete,chklist=" + tmp_chk)
			}

			GEN.COM("chklist_single,action=valor_analysis_drill,show=yes")
			GEN.COM("chklist_pclear")
			GEN.COM("chklist_cupd,chklist=valor_analysis_drill,nact=1,params=((pp_drill_layer="+drill_layer+")(pp_rout_distance=5080)(pp_tests=Hole Separation)(pp_extra_hole_type=Pth\;Npth\;Via)(pp_use_compensated_rout=Skeleton)),mode=regular")
			GEN.COM("chklist_pcopy,chklist=valor_analysis_drill,nact=1")
			GEN.COM("chklist_create,chklist="+tmp_chk)
			GEN.COM("chklist_show,chklist="+tmp_chk)
			GEN.COM("chklist_ppaste,chklist="+tmp_chk+",row=0")
			GEN.COM("chklist_close,chklist=valor_analysis_drill,mode=hide")
			GEN.COM("chklist_cupd,chklist="+tmp_chk+",nact=1,params=((pp_drill_layer="+drill_layer+")(pp_rout_distance=5080)(pp_tests=Hole Separation)(pp_extra_hole_type=Pth\;Npth\;Via)(pp_use_compensated_rout=Skeleton)),mode=regular")
			GEN.COM("chklist_run,chklist="+tmp_chk+",nact=1,area=profile")
			GEN.COM("chklist_create_lyrs,chklist="+tmp_chk+",severity=0")
			GEN.COM("chklist_close,chklist="+tmp_chk+",mode=hide")
			var meas = GEN.getCheckMeas({job:job,step:step,chklist:tmp_chk,nact:1,units:"mm"})
			var closenDrl = [];
			meas.forEach(function(v){
				if(/^closeh [^\s]+ ([^\s]+) [^\s]+ [^\s]+ [^\s]+ [^\s]+ ([^\s]+) ([^\s]+) ([^\s]+) ([^\s]+)/.test(v)){
					closenDrl.push({
						meas:v,
						size:Number(RegExp.$1),
						p1: {x:RegExp.$2, y:RegExp.$3},
						p2: {x:RegExp.$4, y:RegExp.$5}
					})
				}
			})
			closenDrl.forEach(function(item){
				if(item.size < 150){
					GEN.COM("sel_single_feat,operation=select,x="+item.p1.x+",y="+item.p1.y+",cyclic=no")
					GEN.COM("sel_single_feat,operation=select,x="+item.p2.x+",y="+item.p2.y+",cyclic=no")
				}
			})
			// GEN.COM("chklist_close,chklist="+tmp_chk+",mode=hide")

			// if(GEN.isLayerExists({job:job, layer:tmp_drl})){GEN.deleteLayer({job:job , layer: [tmp_drl]})}
			// if(GEN.isLayerExists({job:job, layer:line_drl})){GEN.deleteLayer({job:job , layer: [line_drl]})}
			// GEN.selCopyOther({dest:'layer_name',target_layer:tmp_drl,invert:'no',dx:0,dy:0,size:0})
			// GEN.workLayer({name:tmp_drl,display_number:2,clear_before:'yes'})
			// GEN.selResize({size: 150,corner_ctl:"yes"})

			// // 选中 线  选中非 r*的 选中移动到 槽孔层
			// GEN.selectByFilter({feat_types:"line"})
			// GEN.selectByFilter({exclude_syms:"r*"})
			// if(GEN.getSelectCount() > 0) {
			// 	GEN.selMoveOther({target_layer:line_drl,invert:'no',dx:0,dy:0,size:0})
			// 	GEN.workLayer({name:line_drl,display_number:2,clear_before:'yes'})
			// 	GEN.selRefFeat({layers:tmp_drl, use:'filter', mode:"touch"})
			// 	if(GEN.getSelectCount() > 0) {
			// 		GEN.selCopyOther({dest:"layer_name",target_layer:tmp_drl,invert:'no',dx:0,dy:0,size:0})
			// 	}
			// 	// todo 槽孔层 碰一块的也拷贝回去
			// 	GEN.workLayer({name:tmp_drl,display_number:2,clear_before:'yes'})
			// }	
			// GEN.COM("sel_contourize,accuracy=0,break_to_islands=yes,clean_hole_size=0,clean_hole_mode=x_and_y")
			// GEN.COM("units,type=inch")
			// GEN.COM("sel_cont2pad,match_tol=1,restriction=,min_size=5,max_size=10000,suffix=+++")
			// GEN.units({ type: par.units });  //单位初始化
			// if(GEN.isLayerExists({job:job, layer:tmp_drl + "+++"})){GEN.deleteLayer({job:job , layer: [tmp_drl + "+++"]})}
			// GEN.selectByFilter({include_syms:"*construct*"})
			// GEN.selReverse()
			// if(GEN.getSelectCount()>0) {GEN.selDelete()}
			// GEN.workLayer({name:drill_layer,display_number:2,clear_before:'yes'})
			// GEN.selRefFeat({layers:tmp_drl, use:'filter', mode:"cover"})
			if(GEN.getSelectCount() > 0) {
				GEN.chklistResShow({chklist:tmp_chk,nact:1})
				GEN.PAUSE("please check closen holes")
			}	
		})
		
		
	})


	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}